# coding:utf-8
from functools import wraps
from werkzeug.contrib.cache import RedisCache
from uzwan import config

class CacheRegion(object):
    def __init__(self, redis):
        self.regions = {}
        region_conf = config.CACHE_REGIONS
        for region_name, region_expire in region_conf.items():
            self.regions[region_name] = RedisCache(redis, default_timeout=region_expire, key_prefix=region_name + ':')

    def __call__(self, region_name):
        return self.regions[region_name]

    def cached(self, region_name, timeout=None):
        cache_region = self.regions[region_name]

        def _func_wrapper(func):
            @wraps(func)
            def _arg_wrapper(*args, **kwargs):
                key = func.__name__ + ':' + str(args) + str(kwargs)
                ret = cache_region.get(key)
                if ret:
                    return ret
                ret = func(*args, **kwargs)
                if ret == None:
                    return ret
                cache_region.set(key, ret, timeout=timeout)
                return ret

            return _arg_wrapper

        return _func_wrapper